﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RuYiAdmin.Net.Common.CommonClass.Extensions
{
    /// <summary>
    /// list排序扩展
    /// </summary>
    public static class ListSort
    {
        /// <summary>
        /// List排序
        /// </summary>
        /// <param name="list">list</param>
        /// <param name="strSort">排序字段</param>
        /// <returns>list</returns>
        public static List<T> Sort<T>(this List<T> list, String strSort)
        {
            if (!String.IsNullOrEmpty(strSort))
            {
                var arrySorts = strSort.Split(',');
                foreach (var sort in arrySorts)
                {
                    var arr = sort.Split(' ');
                    var field = arr[0];
                    var direction = arr[1];
                    if (direction.ToUpper().Equals("ASC"))
                    {
                        list = list.OrderBy(t => t.GetType().GetProperty(field)).ToList();
                    }
                    else if (direction.ToUpper().Equals("DESC"))
                    {
                        list = list.OrderByDescending(t => t.GetType().GetProperty(field)).ToList();
                    }
                }
            }
            return list;
        }
    }
}
